<?php

namespace app\common\middleware;

use app\common\controller\Base;
use app\common\service\JsonService;
use think\Response;

/**
 * 初始化
 */
class Init
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try{
            $appName = app('http')->getName();
            //获取控制器
            $controller = str_replace('.', '\\', $request->controller());
            $controller = '\\app\\'.$appName.'\\controller\\' . $controller;
            $controllerClass = invoke($controller);
            if (($controllerClass instanceof Base) === false) {
                JsonService::throw('未继承Base控制器：'.$controller);
            }
            //创建控制器对象（便于后续在中间件中获取控制器的处理操作）
            $request->controllerObject = invoke($controller);
        }catch (\Exception $e){
            JsonService::throw($e->getMessage());
        }

        return $next($request);
    }
}